/*******************************************************************************
 * Copyright (c) 2010 liw.
 * All rights reserved. 
 * 
 * This file is part of VanBus.
 * 
 *     VanBus is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     VanBus is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with VanBus.  If not, see <http://www.gnu.org/licenses/>.
 * Contributors:
 *     liw - initial API and implementation
 ******************************************************************************/
package org.niclab.vanbus.activity;

import org.niclab.vanbus.R;
import org.niclab.vanbus.activity.controller.BusRouteController;
import org.niclab.vanbus.activity.controller.BusStopController;
import org.niclab.vanbus.application.VanBusApplication;
import org.niclab.vanbus.database.ApplicationDataBase;
import org.niclab.vanbus.database.BusRouteDAO;
import org.niclab.vanbus.database.BusStopDAO;
import org.niclab.vanbus.model.BusRoute;
import org.niclab.vanbus.model.BusStop;
import org.niclab.vanbus.utils.CacheUtils;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;

public class FavoritesTab {
	
	private enum AccordionStatus{
		FavoriteRoutes,FavoriteStops
	}
	
	private static final String LOG_TAG ="FavoritesTab";
	
	private TabActivity tabActivity;
	private Context context;
	
	private Button favRouteBtn;
	private ListView favRouteListView;
	private SimpleCursorAdapter favRouteListAdapter;
	
	private Button favStopBtn;
	private ListView favStopListView;
	private SimpleCursorAdapter favStopListAdapter;
	
	private AccordionStatus favStat;
	
	private BroadcastReceiver receiver;

	
	public FavoritesTab(TabActivity tabActivity){
		this.tabActivity = tabActivity;
		this.context = tabActivity.getApplicationContext();
		TabHost tabHost = tabActivity.getTabHost();
		TabHost.TabSpec spec = tabHost.newTabSpec(tabActivity.getString(R.string.favorites_tab_title))
									.setIndicator(tabActivity.getString(R.string.favorites_tab_title))
									.setContent(R.id.favorites_tab);
		tabHost.addTab(spec);
		favStat = AccordionStatus.FavoriteRoutes;

	}
	
	
	public void onCreate(){
		
		favRouteBtn = (Button) tabActivity.findViewById(R.id.favorite_route_button);
		favRouteListView = (ListView) tabActivity.findViewById(R.id.favorite_route_list);
		initializeFavRouteList();
		favRouteListView.setAdapter(favRouteListAdapter);

		favRouteBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(favStat == AccordionStatus.FavoriteRoutes)
					return;
				
				favRouteListView.setVisibility(View.VISIBLE);
				favStopListView.setVisibility(View.GONE);
				
				favStat = AccordionStatus.FavoriteRoutes;
				
			}
		});
		
		favStopBtn = (Button) tabActivity.findViewById(R.id.favorite_stop_button);
		favStopListView = (ListView) tabActivity.findViewById(R.id.favorite_stop_list);
		initializeFavStopList();
		favStopListView.setAdapter(favStopListAdapter);
		favStopBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(favStat==AccordionStatus.FavoriteStops)
					return;
				
				favRouteListView.setVisibility(View.GONE);
				favStopListView.setVisibility(View.VISIBLE);
				
				favStat = AccordionStatus.FavoriteStops;
					
				
			}
		});
		
		
		registerBroadcastReceiver();
	}
	
	public void onDestroy(){
		tabActivity.unregisterReceiver(receiver);
	}

	private void registerBroadcastReceiver(){
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(context.getString(R.string.favorites_tab_route_update));
		intentFilter.addAction(context.getString(R.string.favorites_tab_stop_update));
		receiver = new FavListUpdateBroadcastReciver();
		tabActivity.registerReceiver(receiver , intentFilter);
	}

	private Cursor getFavRouteCursor(){
		BusRouteDAO routeDao = new BusRouteDAO(ApplicationDataBase.getSQLiteOpenHelper());
		Cursor routeCursor = routeDao.getSortedFavoriteRoutes();
		return routeCursor;
	}

	private void initializeFavRouteList() {
		
		Cursor routeCursor = getFavRouteCursor();
		String[] cols = {"ROUTE_ID","NAME","DIR"};
		int[] views = {R.id.favorite_route_id,R.id.favorite_route_name,R.id.favorite_route_dir};
		favRouteListAdapter = new SimpleCursorAdapter(context,R.layout.favorite_route_row, routeCursor, cols,views);
		favRouteListAdapter.setViewBinder(new ViewBinder(){

			@Override
			public boolean setViewValue(View view, Cursor cursor,
					int columnIndex) {
				if(columnIndex==2){
					
					String value = cursor.getString(columnIndex);
					((TextView)view).setText(value.substring(value.indexOf('-')+1));
					
					return true;
				}
				return false;
			}
			
		});
		
		favRouteListView.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				Cursor cursor= (Cursor) favRouteListAdapter.getItem(position);
	          
					//hit the data cache
					BusRouteController routeCtr = new BusRouteController();
					
					BusRoute route = routeCtr.createBusRouteFromCacheAndDB(cursor);
	
					
					
					//register the currently selected bus route
					VanBusApplication app = (VanBusApplication)tabActivity.getApplication();
					String key = route.getRouteId()+route.getRouteDir();
					app.saveTempData(key, route);
					
					//start the stops list activity
					Intent startStopListIntent = new Intent();
					startStopListIntent.setClass(tabActivity,StopListOfRouteAct.class);
					startStopListIntent.putExtra(tabActivity.getString(R.string.currently_selected_bus_route), key);
					
					tabActivity.startActivity(startStopListIntent);
	            
			}
			
		});
		
		
		
	}
	
	private Cursor getFavStopCursor(){
		BusStopDAO stopDAO = new BusStopDAO(ApplicationDataBase.getSQLiteOpenHelper());
		Cursor stopCursor = stopDAO.getFavoriteStops();
		return stopCursor;
	}
	
	private void initializeFavStopList(){
		
		Cursor stopCursor = getFavStopCursor();
		String[] cols={"NAME","STOP_ID"};
		int[] views={R.id.favorite_stop_name,R.id.favorite_stop_id};
		favStopListAdapter= new SimpleCursorAdapter(context,R.layout.favorite_stop_row,stopCursor,cols,views);
		
		favStopListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				
				Cursor cursor = (Cursor) favStopListAdapter.getItem(position);
				BusStop stop = new BusStopController().createBusStopFromDB(cursor);
				
				//register the currently selected bus route to have the be able to retrieve
				
				VanBusApplication app = (VanBusApplication)tabActivity.getApplication();
				String key=stop.getStopId();
				app.saveTempData(key, stop);
				
				//start the stops list activity
				Intent startRouteListIntent = new Intent();
				startRouteListIntent.setClass(context,RouteListOfStopAct.class);
				startRouteListIntent.putExtra(context.getString(R.string.currently_selected_bus_stop), key);
				
				tabActivity.startActivity(startRouteListIntent);
				
				
				
				
			}
			
			
		});
			
	}

	
	public class FavListUpdateBroadcastReciver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(context.getString(R.string.favorites_tab_route_update))){

				favRouteListAdapter.getCursor().requery();
			
			
			}else if(intent.getAction().equals(context.getString(R.string.favorites_tab_stop_update))){

				favStopListAdapter.getCursor().requery();
				
			}
			
			
		}
		
	}

}
